package com.atguigu.executor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@EnableConfigurationProperties(MyThreadPoolProperties.class)
@Configuration
public class MyThreadPool {
    @Autowired
    private MyThreadPoolProperties myProperties;

    @Bean
    public ThreadPoolExecutor myExecutor () {
        /**
         * 高并发场景下 150线程进来
         *  16个线程会立即得到处理
         *  扩展再开16个线程处理任务
         *  100个线程会进入到队列中等待
         *  还剩余18个线程会被采用拒绝策略处理
         *  采用什么队列好
         *      ArrayBlockingQueue
         *          空间碎片问题，导致内存空间不连续
         *      LinkedBlockingQueue
         *          不会引起碎片问题
         */
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(myProperties.getCorePoolSize(),
                myProperties.getMaximumPoolSize(),
                myProperties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(myProperties.getQueueLength()),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        return poolExecutor;
    }
}

